from datetime import datetime
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from pyplog.blog.models import Post
from pyplog.config import config

def key_filter(request, key_class = None, slug = None, page = "1"):
	"""
	View to filter blog posts by a certain key object.
	"""
	if not page:
		page = "1"
		
	if key_class is None:
		feed_url = reverse("post-feed", kwargs = { "url" : "all" })
		key = None
		posts = Post.public_objects.all()
	else:
		key = get_object_or_404(key_class, slug = slug)
		feed_url = key.get_feed_url()
		posts = key.posts.all()
		
	p = Paginator(posts, config.blog_posts_per_page)
	page_obj = p.page(page)
	context_data = {
		"key" : key,
		"is_paginated" : (len(posts) > config.blog_posts_per_page),
		"feed_url" : feed_url,
		"page" : int(page),
		"page_obj" : page_obj,
		"paginator" : p,
		"post_list" : page_obj.object_list,
	}
	
	return render_to_response(
		"blog/post_list.html",
		context_data,
		context_instance = RequestContext(request),
	)
